<?php

namespace app\api\controller;
use app\common\controller\Api;
use think\Validate;
use think\Loader;
use think\Page;
use think\Db;
use \app\admin\model\VolunteerAudit;
use \app\admin\model\Volunteer as Volunteers;
use \app\admin\model\Staff;
use \app\admin\model\CaringTask;
use \app\admin\model\TrainingTasks;
class Usertask extends Api
{ 
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $user_id = 0;
    protected $volunteer_info = null;
    protected $vmodel = null;
    protected $cmodel = null;
    protected $tmodel = null;
    protected $noCheckVolunteer = ['applyinfo','apply'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->vmodel = new Volunteers;
        $this->cmodel = new CaringTask;
        $this->tmodel = new TrainingTasks;
        $this->volunteer_info = $this->vmodel
                                ->where(['user_id'=>$this->auth->id])
                                ->find();

        $actionname = strtolower($this->request->action());
        // 不需要檢查義工的接口
        if ( !in_array($actionname, $this->noCheckVolunteer) && !$this->volunteer_info ) {
            $this->success('請求成功',[]);
        }
    }

    /**
     * @MethodName 獲取關懷任務列表
     * @Author     Allen
     * @DateTime   2021-10-08T10:49:13+0800
     * @param      string
     * @return     [type]
     */
    public function getUserCaringTaskList($value='')
    {
        $status = $this->request->post("status", 0);

        $where = ['o.status'=>['neq','0'],'o.volunteer_id'=>$this->volunteer_info['id']];
        if ( $status ) {
            $where['o.status'] = $status;
        }
        $total = $this->cmodel
                ->alias('c')
                ->where($where)
                ->join('user u','c.user_id = u.id')
                ->join('caring_task_order o','o.caring_task_id = c.id')
                ->count();

        $page = new Page($total,10);
        $list = $this->cmodel
                ->alias('c')
                ->field('c.id,c.task_no,u.nickname,u.avatar,c.province,c.city,c.district,c.address,c.arrivaltime,c.returnvisittime,o.order_receiving_time,o.completiontime,c.workinghours,c.exp,c.score,c.peoplenum,o.status')
                ->where($where)
                ->join('user u','c.user_id = u.id')
                ->join('caring_task_order o','o.caring_task_id = c.id')
                ->limit($page->firstRow.','.$page->listRows)
                ->order('c.id desc')
                ->select();

        foreach ($list as $key => &$value) {
                $region_address = db('region')->where(['id'=>$value['province']])->value('name');
                $city = db('region')->where(['id'=>$value['city']])->value('name');
                if ( $city ) {
                    $region_address = $region_address.$city;
                    $district = db('region')->where(['id'=>$value['district']])->value('name');
                    if ( $district ) {
                        $region_address = $region_address.$district;
                    }
                }
                $region_address = $region_address.$value['address'];
                $value['region_address'] = $region_address?$region_address:'';
                unset($value['province']);
                unset($value['city']);
                unset($value['district']);
                unset($value['address']);
        }
        unset($value);

        $data = ['total'=>$total,'listrows'=>$page->listRows,'totalpages'=>$page->totalPages,'data'=>$list];
        $this->success('請求成功',$data);
    }

    /**
     * @MethodName 獲取關懷任務詳情
     * @Author     Allen
     * @DateTime   2021-10-08T10:49:13+0800
     * @param      string
     * @return     [type]
     */
    public function getUserCaringTaskInfo($value='')
    {
        $rq_data = $this->request->param();
        $validate = Loader::validate('VolunteerAudit');
        if (!$validate->scene('task')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $id = $rq_data['id'];

        $where = ['c.id'=>$id,'o.status'=>['neq','0'],'o.volunteer_id'=>$this->volunteer_info['id']];

        $info = $this->cmodel
                ->alias('c')
                ->field('c.id,o.id as order_id,c.task_no,u.nickname,u.avatar,c.province,c.city,c.district,c.address,c.arrivaltime,c.returnvisittime,o.order_receiving_time,o.completiontime,c.workinghours,c.exp,c.score,c.peoplenum,o.content,o.status')
                ->where($where)
                ->join('user u','c.user_id = u.id')
                ->join('caring_task_order o','o.caring_task_id = c.id')
                ->find();
        if ( !$info ) {
            $this->success('請求成功',[]);
        }

        $region_address = db('region')
                        ->where(['id'=>$info['province']])
                        ->value('name');

        $city = db('region')
                ->where(['id'=>$info['city']])
                ->value('name');

        if ( $city ) {
            $region_address = $region_address.$city;
            $district = db('region')
                        ->where(['id'=>$info['district']])
                        ->value('name');

            if ( $district ) {
                $region_address = $region_address.$district;
            }
        }
        $region_address = $region_address.$info['address'];
        $info['region_address'] = $region_address?$region_address:'';
        $info['images'] = [];
        // 已完成
        if ( $info['status'] == '2' ) {
            $info['images'] = db('upload_images')
                                ->where(['type'=>'1','relation_id'=>$info['order_id']])
                                ->column('images');
        }
        unset($info['province']);
        unset($info['city']);
        unset($info['district']);
        unset($info['address']);
        unset($info['order_id']);

        $this->success('請求成功',$info);
    }

    /**
     * @MethodName 提交關懷任務
     * @Author     Allen
     * @DateTime   2021-10-08T11:31:05+0800
     * @param      string
     * @return     [type]
     */
    public function submitCaringTask($value='')
    {
        $time = time();
        $rq_data = $this->request->param();
        $validate = Loader::validate('VolunteerAudit');
        if (!$validate->scene('submittask')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $where = ['o.status'=>'1','o.volunteer_id'=>$this->volunteer_info['id']];
        $info = $this->cmodel
                ->alias('c')
                ->field('c.id,c.task_no,o.id as order_id,u.nickname,u.avatar,c.province,c.city,c.district,c.address,c.arrivaltime,c.returnvisittime,c.workinghours,c.score,c.peoplenum,c.exp')
                ->where(['c.id'=>$rq_data['id']])
                ->where($where)
                ->join('user u','c.user_id = u.id')
                ->join('caring_task_order o','o.caring_task_id = c.id')
                ->find();

        if ( !$info ) {
            $this->error('未找到該任務,請刷新頁面');
        }

        $order_info = db('caring_task_order')
                ->where(['id'=>$info->order_id,'status'=>'1','volunteer_id'=>$this->volunteer_info['id']])
                ->find();

        if ( !$order_info ) {
            $this->error('未找到該任務,請刷新頁面');
        }

        Db::startTrans();
            try {
                $status = db('caring_task_order')
                        ->where(['id'=>$order_info['id']])
                        ->update(['content'=>$rq_data['content'],'status'=>'2','updatetime'=>$time,'completiontime'=>$time]);

                if ( !$status ) {
                    Db::rollback();
                    $this->error('操作失敗');
                }

                if ( isset($rq_data['images']) && $rq_data['images'] ) {
                    $images_arr_buf = explode(',', $rq_data['images']);
                    $images_arr = [];
                    foreach ($images_arr_buf as $key => $value) {
                        $images_arr[] = ['images'=>$value,'type'=>1,'relation_id'=>$order_info['id']];
                    }
                    db('upload_images')->insertAll($images_arr);
                }

                // 加經驗和工時
                $status = addTaskLog($this->user_id,'1',$info->task_no,$info->workinghours,$info->score,$info->exp,$time);
                if ( !$status ) {
                    Db::rollback();
                    $this->error('操作失敗');
                }

                // 判斷子任務是否都完成
                $count = db('caring_task_order')->where(['caring_task_id'=>$rq_data['id'],'status'=>'1'])->count();
                if ( !$count ) {
                    $this->cmodel->where(['id'=>$rq_data['id']])->update(['status'=>'2','completiontime'=>$time]);
                }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();
            $this->error('操作失敗,'.$e->getMessage());
        }

        $this->success('操作成功');

    }

    /**
     * @MethodName 獲取培訓任務列表
     * @Author     Allen
     * @DateTime   2021-10-08T10:49:13+0800
     * @param      string
     * @return     [type]
     */
    public function getUserTrainingTaskList($value='')
    {
        $status = $this->request->post("status", 0);

        $where = ['o.status'=>['neq','0'],'o.volunteer_id'=>$this->volunteer_info['id']];
        if ( $status ) {
            $where['o.status'] = $status;
        }
        $total = $this->tmodel
                ->alias('t')
                ->where($where)
                ->join('training_task_order o','o.training_task_id = t.id')
                ->count();

        $page = new Page($total,10);
        $list = $this->tmodel
                ->alias('t')
                ->field('t.id,t.task_no,t.type,t.province,t.city,t.district,t.address,t.arrivaltime,o.order_receiving_time,o.completiontime,t.workinghours,t.exp,t.score,t.content,o.status')
                ->where($where)
                ->join('training_task_order o','o.training_task_id = t.id')
                ->limit($page->firstRow.','.$page->listRows)
                ->order('t.id desc')
                ->select();
        foreach ($list as $key => &$value) {
                $region_address = db('region')
                                ->where(['id'=>$value['province']])
                                ->value('name');

                $city = db('region')
                        ->where(['id'=>$value['city']])
                        ->value('name');

                if ( $city ) {
                    $region_address = $region_address.$city;
                    $district = db('region')
                            ->where(['id'=>$value['district']])
                            ->value('name');
                    if ( $district ) {
                        $region_address = $region_address.$district;
                    }
                }
                $region_address = $region_address.$value['address'];
                $value['region_address'] = $region_address?$region_address:'';
                unset($value['province']);
                unset($value['city']);
                unset($value['district']);
                unset($value['address']);
        }
        unset($value);

        $data = ['total'=>$total,'listrows'=>$page->listRows,'totalpages'=>$page->totalPages,'data'=>$list];
        $this->success('請求成功',$data);
    }

    /**
     * @MethodName 獲取培訓任務詳情
     * @Author     Allen
     * @DateTime   2021-10-08T11:31:05+0800
     * @param      string
     * @return     [type]
     */
    public function getUserTrainingTaskInfo($value='')
    {
        $time = time();
        $rq_data = $this->request->param();
        $validate = Loader::validate('VolunteerAudit');
        if (!$validate->scene('task')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $id = $rq_data['id'];
        $where = ['t.id'=>$id,'o.status'=>['neq','0'],'o.volunteer_id'=>$this->volunteer_info['id']];
        $info = $this->tmodel
                ->alias('t')
                ->field('t.id,o.id as order_id,t.task_no,t.type,t.province,t.city,t.district,t.address,t.arrivaltime,o.order_receiving_time,o.completiontime,t.workinghours,t.exp,t.score,t.content,o.content as user_content,o.score as user_score,o.status')
                ->where($where)
                ->join('training_task_order o','o.training_task_id = t.id')
                ->find();

        if ( !$info ) {
            $this->error('未找到該任務,請刷新頁面');
        }
        $order_info = db('training_task_order')
                ->where(['id'=>$info->order_id,'status'=>['neq','0'],'volunteer_id'=>$this->volunteer_info['id']])
                ->find();

        if ( !$order_info ) {
            $this->error('未找到該任務,請刷新頁面');
        }


        $region_address = db('region')
                            ->where(['id'=>$info['province']])
                            ->value('name');

        $city = db('region')
                ->where(['id'=>$info['city']])
                ->value('name');

        if ( $city ) {
            $region_address = $region_address.$city;
            $district = db('region')
                        ->where(['id'=>$info['district']])
                        ->value('name');

            if ( $district ) {
                $region_address = $region_address.$district;
            }
        }
        $region_address = $region_address.$info['address'];
        $info['region_address'] = $region_address?$region_address:'';
        $info['user_content'] = $info['user_content']?$info['user_content']:'';
        $info['images'] = [];
        // 已完成
        if ( $info['status'] == '2' ) {
            $info['images'] = db('upload_images')
                            ->where(['type'=>'2','relation_id'=>$info['order_id']])
                            ->column('images');
        }
        unset($info['province']);
        unset($info['city']);
        unset($info['district']);
        unset($info['address']);
        unset($info['order_id']);

        $this->success('請求成功',$info);

    }

    /**
     * @MethodName 提交培訓任務
     * @Author     Allen
     * @DateTime   2021-10-08T11:31:05+0800
     * @param      string
     * @return     [type]
     */
    public function submitTrainingTask($value='')
    {
        $time = time();
        $rq_data = $this->request->param();
        $validate = Loader::validate('VolunteerAudit');
        if (!$validate->scene('submitTtask')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $code = decode($rq_data['code']);
        $code_buf = explode('_', $code);
        if ( !isset($code_buf[2]) ) {
            $this->error('二維碼錯誤');
        }

        $where = ['t.status'=>'1','o.status'=>'1','o.volunteer_id'=>$this->volunteer_info['id']];
        $info = $this->tmodel
                ->alias('t')
                ->field('t.id,o.id as order_id,t.task_no,t.type,t.province,t.city,t.district,t.address,t.arrivaltime,o.order_receiving_time,o.completiontime,t.workinghours,t.score,t.content,o.content as user_content,t.exp,o.score as user_score,o.status')
                ->where(['t.id'=>$rq_data['id']])
                ->where($where)
                ->join('training_task_order o','o.training_task_id = t.id')
                ->find();

        if ( !$info ) {
            $this->error('未找到該任務,請刷新頁面');
        }
        $order_info = db('training_task_order')
                ->where(['id'=>$info->order_id,'status'=>'1','volunteer_id'=>$this->volunteer_info['id']])
                ->find();

        if ( !$order_info ) {
            $this->error('未找到該任務,請刷新頁面');
        }

        $buf = 'training_tasks_'.$info->id;
        if ( $buf !== $code ) {
            $this->error('二維碼錯誤');
        }

        Db::startTrans();
            try {
                $status = db('training_task_order')
                        ->where(['id'=>$order_info['id']])
                        ->update(['content'=>$rq_data['content'],'score'=>$rq_data['score'],'status'=>'2','updatetime'=>$time,'completiontime'=>$time]);

                if ( !$status ) {
                    Db::rollback();
                    $this->error('操作失敗');
                }

                if ( isset($rq_data['images']) && $rq_data['images'] ) {
                    $images_arr_buf = explode(',', $rq_data['images']);
                    $images_arr = [];
                    foreach ($images_arr_buf as $key => $value) {
                        $images_arr[] = ['images'=>$value,'type'=>'2','relation_id'=>$order_info['id']];
                    }
                    db('upload_images')->insertAll($images_arr);
                }
                // 加經驗和工時
                $status = addTaskLog($this->user_id,'2',$info->task_no,$info->workinghours,$info->score,$info->exp,$time);
                if ( !$status ) {
                    Db::rollback();
                    $this->error('操作失敗');
                }

                // 判斷子任務是否都完成
                $count = db('training_task_order')
                        ->where(['training_task_id'=>$rq_data['id'],'status'=>'1'])
                        ->count();
                        
                if ( !$count ) {
                    $this->tmodel->where(['id'=>$rq_data['id']])->update(['status'=>'2','completiontime'=>$time]);
                }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();
            $this->error('操作失敗,'.$e->getMessage());
        }

        $this->success('操作成功');
    }


    /**
     * @MethodName 獲取評分記錄
     * @Author     Allen
     * @DateTime   2021-10-09T17:46:18+0800
     * @param      string
     * @return     [type]
     */
    public function getScoringList($value='')
    {

        $where = ['t.status'=>'2','o.status'=>'2','o.volunteer_id'=>$this->volunteer_info['id']];

        $total = $this->tmodel
                ->alias('t')
                ->where($where)
                ->join('training_task_order o','o.training_task_id = t.id')
                ->count();

        $page = new Page($total,10);
        $list = $this->tmodel
                ->alias('t')
                ->field('t.id,t.task_no,o.score,o.completiontime')
                ->where($where)
                ->join('training_task_order o','o.training_task_id = t.id')
                ->limit($page->firstRow.','.$page->listRows)
                ->order('t.id desc')
                ->select();

        $data = ['total'=>$total,'listrows'=>$page->listRows,'totalpages'=>$page->totalPages,'data'=>$list];

        $this->success('請求成功',$data);
    }


}